import { defineStore } from 'pinia'

/**
 * 相册状态管理
 */
export const useAlbumStore = defineStore('album', {
  state: () => ({
    // 相册列表
    albums: [] as any[],
    
    // 当前相册
    currentAlbum: null as any,
    
    // 分页信息
    pagination: {
      page: 1,
      limit: 50,
      total: 0,
      totalPages: 0
    },
    
    // 加载状态
    loading: false,
    
    // 当前相册中的照片
    albumPhotos: [] as any[]
  }),
  
  getters: {
    // 获取相册总数
    albumCount: (state) => state.pagination.total,
    
    // 获取当前页相册
    currentPageAlbums: (state) => state.albums,
    
    // 获取当前相册中的照片数量
    currentAlbumPhotoCount: (state) => state.albumPhotos.length
  },
  
  actions: {
    // 获取相册列表
    async fetchAlbums(params: any = {}) {
      this.loading = true
      
      try {
        const response = await window.electronAPI.albums.getList({
          page: params.page || this.pagination.page,
          limit: params.limit || this.pagination.limit,
          orderBy: params.orderBy || 'created_at',
          orderDirection: params.orderDirection || 'desc'
        })
        
        if (response.success) {
          this.albums = response.data.albums
          this.pagination = {
            page: response.data.page,
            limit: response.data.limit,
            total: response.data.total,
            totalPages: response.data.totalPages
          }
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取相册列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取相册详情
    async fetchAlbumById(id: number) {
      this.loading = true
      
      try {
        const response = await window.electronAPI.albums.getById({ id })
        
        if (response.success) {
          this.currentAlbum = response.data
          this.albumPhotos = response.data.photos || []
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取相册详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 创建相册
    async createAlbum(name: string, description?: string) {
      try {
        const response = await window.electronAPI.albums.create({ name, description })
        
        if (response.success) {
          // 添加到本地相册列表
          this.albums.unshift(response.data)
          
          // 更新总数
          this.pagination.total += 1
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('创建相册失败:', error)
        throw error
      }
    },
    
    // 更新相册信息
    async updateAlbum(id: number, updates: any) {
      try {
        const response = await window.electronAPI.albums.update({ id, updates })
        
        if (response.success) {
          // 更新本地相册列表中的对应项
          const index = this.albums.findIndex(album => album.id === id)
          if (index !== -1) {
            this.albums[index] = { ...this.albums[index], ...updates }
          }
          
          // 更新当前相册
          if (this.currentAlbum && this.currentAlbum.id === id) {
            this.currentAlbum = { ...this.currentAlbum, ...updates }
          }
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('更新相册失败:', error)
        throw error
      }
    },
    
    // 删除相册
    async deleteAlbum(id: number) {
      try {
        const response = await window.electronAPI.albums.delete({ id })
        
        if (response.success) {
          // 从本地相册列表中移除
          this.albums = this.albums.filter(album => album.id !== id)
          
          // 如果是当前相册，清空当前相册
          if (this.currentAlbum && this.currentAlbum.id === id) {
            this.currentAlbum = null
            this.albumPhotos = []
          }
          
          // 更新总数
          this.pagination.total -= 1
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('删除相册失败:', error)
        throw error
      }
    },
    
    // 向相册添加照片
    async addPhotoToAlbum(albumId: number, photoId: number) {
      try {
        const response = await window.electronAPI.albums.addPhoto({ albumId, photoId })
        
        if (response.success) {
          // 如果是当前相册，添加到照片列表
          if (this.currentAlbum && this.currentAlbum.id === albumId) {
            // 这里需要获取照片详情，简化处理
            // 实际应用中可能需要从照片store获取
            this.albumPhotos.push({ id: photoId })
          }
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('添加照片到相册失败:', error)
        throw error
      }
    },
    
    // 从相册移除照片
    async removePhotoFromAlbum(albumId: number, photoId: number) {
      try {
        const response = await window.electronAPI.albums.removePhoto({ albumId, photoId })
        
        if (response.success) {
          // 如果是当前相册，从照片列表移除
          if (this.currentAlbum && this.currentAlbum.id === albumId) {
            this.albumPhotos = this.albumPhotos.filter(photo => photo.id !== photoId)
          }
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('从相册移除照片失败:', error)
        throw error
      }
    },
    
    // 设置当前页
    setPage(page: number) {
      this.pagination.page = page
    },
    
    // 设置每页数量
    setLimit(limit: number) {
      this.pagination.limit = limit
    },
    
    // 清空相册列表
    clearAlbums() {
      this.albums = []
      this.currentAlbum = null
      this.albumPhotos = []
    }
  }
})